package com.ijiuchuang.jc_localization.model;

import com.ijiuchuang.jc_localization.app.Config;
import com.ijiuchuang.jc_localization.bean.cache.DeviceListCache;
import com.ijiuchuang.jc_localization.bean.lite.Tag;
import com.ijiuchuang.jc_localization.contract.DeviceListContract;
import com.litesuits.orm.LiteOrm;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Created by Veev on 2016/6/14
 *
 * @link 384506557@qq.com
 */
public class DeviceListModel implements DeviceListContract.Model {

    private LiteOrm liteOrm = Config.liteOrm;

    @Override
    public void getDatas(Action1<List<Tag>> action1) {
        Observable
                .create(new Observable.OnSubscribe<List<Tag>>() {
                    @Override
                    public void call(Subscriber<? super List<Tag>> subscriber) {
                        List<Tag> tagList = liteOrm.query(Tag.class);
                        subscriber.onNext(tagList);
                    }
                })
                .subscribe(action1);
    }

    @Override
    public void deleteData(Object tag) {
        liteOrm.delete(tag);
        Tag tag1 = (Tag) tag;
        // 移除缓存
        DeviceListCache.getInstance().removeCache(tag1.getMac());
    }

    @Override
    public void changeName(Tag tag, String name) {
        tag.setName(name);
        liteOrm.update(tag);
        // 修改缓存中设备名
        DeviceListCache.getInstance().setName(tag.getMac(), name);
    }
}
